package com.lxl.message;

import java.util.*;

import static com.lxl.message.TemplateStringUtils.*;

//模板文件的元数据
public class TemplateMeta {

    public String type;//转化类型
    public String encoding;//编码格式
    public TemplateStructure structure;//模板结构

    public TemplateMeta(){
        type = "";
        encoding = "UTF-8";
        structure = null;
    }

    public TemplateMeta(String text){
        this();

        text = removeBracket(removeBlank(text));
        String[] coreKVArray = text.split(";");
        for (int i =0; i<coreKVArray.length; i++){
            String[] coreKV = getKeyAndValue(coreKVArray[i]);
            switch (coreKV[0]){
                case "type":{
                    this.type = coreKV[1];
                    break;
                }
                case "encoding":{
                    this.encoding = coreKV[1];
                    break;
                }
                case "structure":{
                    structure = TemplateStructure.build(removeBracket(coreKV[1]));
                    break;
                }
                default:break;
            }
        }
    }



    public static void traverse(Map<String, Object> structure){
        for (Map.Entry<String, Object> entry : structure.entrySet()){
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Map){
                System.out.println("in array:"+key);
                traverse((Map<String, Object>) value);
            }else if (value instanceof String){
                System.out.println("in key-value:[ "+key+":"+value+" ]");
            }
        }
    }

    public static void traverse2(Map<String, Object> structure){
        Iterator<Map.Entry<String, Object>> iterator= structure.entrySet().iterator();
        Stack<Iterator<Map.Entry<String, Object>>> stack = new Stack<>();
        Stack<String> tagStack = new Stack<>();
        while(iterator.hasNext() || !stack.isEmpty()) {
            if (!iterator.hasNext() && !stack.isEmpty()){
                iterator = stack.pop();
                System.out.println("out array:"+tagStack.pop());
                continue;
            }

            Map.Entry<String, Object> entry = iterator.next();
            if (entry.getValue() instanceof  String){
                System.out.println("in key-value:[ "+entry.getKey()+":"+entry.getValue()+" ]");
            }else if (entry.getValue() instanceof Map){
                System.out.println("in array:"+entry.getKey());
                stack.push(iterator);
                tagStack.push(entry.getKey());
                iterator = ((Map<String, Object>)entry.getValue()).entrySet().iterator();
            }
        }
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder("taskType:"+type+"\n")
                .append(structure)
                .append("encoding:"+ encoding +"\n");
        return str.toString();
    }
}
